package vn.edu.nuce.bean;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Redirect implements Filter {

	public void init(FilterConfig filterConfig) throws ServletException {
	}

	private boolean checkPermission(Object isQuanLy,String url){
		String[] quanLyUrl = {"quan-ly","quan-ly-lich-su","quan-ly-phong"};
        String[] giaoVienUrl = {"dang-ky","lich-su-dang-ky"};
        if(isQuanLy!=null){
	        if ((Boolean) isQuanLy){
	        	for (String item:giaoVienUrl){
	        		if (item.equals(url)){
	        			return false;
	        		}
	        	}
	        } else {
	        	for (String item:quanLyUrl){
	        		if (item.equals(url)){
	        			return false;
	        		}
	        	}
	        }
        }
        return true;
	}
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String pageRequested = req.getRequestURI().toString();
        String linkRequest = pageRequested.substring(pageRequested.lastIndexOf("/") + 1);
        String url = linkRequest.split("\\.")[0];
        String urlImg="";
        try {
        	urlImg= pageRequested.split("\\/")[2];
		} catch (Exception e) {
		}
        req.setCharacterEncoding("UTF-8");
        res.setContentType("text/html; charset=UTF-8");
        Object obj = req.getSession().getAttribute(LoginBean.AUTH_ID);
        Object isQuanLy = req.getSession().getAttribute(LoginBean.AUTH_QL);
       
        String timeoutUrl;
        if (req.getSession() != null && req.getSession().isNew()) {
            timeoutUrl = req.getContextPath() + "/index.xhtml";
            res.sendRedirect(timeoutUrl);
            return;
        }
        if (obj == null && !pageRequested.equals(req.getContextPath() + "/index.xhtml") && !urlImg.equals("javax.faces.resource") && !urlImg.equals("images")) {
            timeoutUrl = req.getContextPath() + "/index.xhtml";
            res.sendRedirect(timeoutUrl);
        } else if(!checkPermission(isQuanLy,url)){
        	timeoutUrl = req.getContextPath() + "/thong-bao.xhtml";
        	res.sendRedirect(timeoutUrl);
        } else {
            chain.doFilter(req, res);
        }
	}

	public void destroy() {
	}

}
